// 配置文件 公共方法
import Vue from 'vue'

import { baseUrl } from './api'

//静态资源路径 预留
const imgUrl = baseUrl + '/v1/file/images'

//提示
const tipMsg =(title,icon,time,mask)=>{
        title = title == undefined ? "系统繁忙" : title;
        icon = icon == undefined ? "none" : icon;
        time = time == undefined ? 1500 : time;
        mask = mask == undefined ? true : mask;
        uni.showToast({
            title:title,
            icon:icon,
            mask:mask,
            duration:time
        })
}

// 设置title
const setTitle = title =>{
	//如果需要在页面进入时设置标题，可以在onReady内执行，以避免被框架内的修改所覆盖
	//如果必须在onShow内执行需要延迟一小段时间
	uni.setNavigationBarTitle({
	    title: title
	})
}

//验证手机号
const checkPhone = phone=>{
    if(!(/^1[23456789]\d{9}$/.test(phone))){
        uni.showToast({
            title:"手机号格式不正确",
            icon:'none'
        })
        return false;
    }
    return true;
}

// 验证码邮箱
const checkEmail = email=>{
	if(!(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(email))){
		uni.showToast({
		    title:"邮箱格式不正确",
		    icon:'none'
		})
		return false;
	}
	return true;
}

// 页面跳转
const jump = (url, params, tabBar) => {
    tabBar
        ? uni.reLaunch({
              url: url,
          })
        : uni.navigateTo({
              url: url + params,
          });
};

const nowDate = ()=>{
	let date = new Date();
	let seperator1 = "-";
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	let currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate
}

const nowTime = ()=>{
	let date = new Date();
	let seperator1 = ":";
	let hours = date.getHours();
	let min = date.getMinutes();
	if (hours >= 0 && hours <= 9) {
		hours = "0" + hours;
	}
	if (min >= 0 && min <= 9) {
		min = "0" + min;
	}
	return hours + seperator1 + min
}

const back = (delta) =>{
	uni.navigateBack({
		delta:delta || 1
	})
}

function upload(that,callback) {
	uni.chooseImage({
		count: 1, //默认9
		sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
		success: function(res) {
			console.log(res)
			that.$http
			.upload('/v1/file/images', {
				filePath: res.tempFilePaths[0],
				name: 'file'
			})
			.then(res => {
				callback(res.data.data.url)
			})
			.catch(err => {
				console.log(err);
			})
		}
	})
}

const getCode = ()=>{
	if (document.URL.match(/\?.*#/)) {
	    let temp = document.URL.match(/\?.*#/)[0]
	    if (temp.match(/=.*&/)) {
	      // 解析Code
	      let code = temp.match(/=.*&/)[0]
	      code = code.substr(1, code.length) // 去掉 ?
	      code = code.substr(0, code.length - 1)  // 去掉 #
	      // 重置URL(去掉code参数，避免重复调用)
	      window.history.pushState({}, 0, document.URL.replace(temp.substr(0, temp.length - 1), ''))
		  return code
	    }
		return false
	}
	return false
}

const getParams = (key)=>{
	const params = {}
	window.location.hash.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>params[k]=v)
	return key ? params[key] : params
}


const cookie = {
	set: function(name, value){
	  // 缓存过期时间
	  let Days = 30
	  let exp = new Date()
	  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
	  document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
	},
	get: function(name){
	  let arr = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
	  let reg = arr
	  arr = document.cookie.match(reg)
	  if (arr) {
	    return unescape(arr[2])
	  }else{
	    return null
	  }
	},
	del: function(name){
	  let exp = new Date()
	  exp.setTime(exp.getTime() - 1)
	  let cval = this.cookie.get(name)
	  if (cval != null) {
	    document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
	  }
	}
}

const h5Copy = (content)=>{
	if (!document.queryCommandSupported('copy')) {
		// 不支持
		return false
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	textarea.remove()
	return result
}

module.exports = {
	tipMsg,
	checkPhone,
	checkEmail,
	jump,
	setTitle,
	nowDate,
	nowTime,
	back,
	imgUrl,
	upload,
	getCode,
	getParams,
	cookie,
	h5Copy,
	imgUpApi
}